﻿
namespace Jhecis.Service
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Oracle.ManagedDataAccess;
    using System.Data;

    using Oracle.ManagedDataAccess.Client;

    public class BingLiBLL
    {
        public List<CDADiagnose> ALLCDADia = new List<CDADiagnose>();
        public BingLiBLL() 
        {
          
           
        }
        /// <summary>
        /// 获取时间段内，写病历的患者
        /// </summary>
        /// <returns></returns>
        public DataTable GetAllPatients(string startTime, string endTime)
        {
            StringBuilder str = new StringBuilder();
            str.Append("select distinct patient_id from jhmr_file_index jf ");
            str.Append("where jf.delete_flag=0 and jf.create_date_time between to_date('" + startTime + "','yyyy-mm-dd hh24:mi:ss') and to_date('" + endTime + "','yyyy-mm-dd hh24:mi:ss') ");
            OracleParameter[] param3 = new OracleParameter[] { };
            DataTable DtNew = OrcleHelper.ExecToSqlGetTable(str.ToString(), param3, OrcleHelper.JhecisCon);
            return DtNew;
        }
        /// <summary>
        /// 通过patientid查患者
        /// </summary>
        /// <returns></returns>
        public DataTable GetAllPatientByPatientid(string patientid)
        {
            StringBuilder str = new StringBuilder();
            str.Append("select * from jhmr_file_index jf left join triage_patientvisit tp on jf.patient_id=tp.pvid ");
            str.Append("where jf.delete_flag=0 and tp.patientid='"+ patientid + "' ");
            OracleParameter[] param3 = new OracleParameter[] { };
            DataTable DtNew = OrcleHelper.ExecToSqlGetTable(str.ToString(), param3, OrcleHelper.JhecisCon);
            return DtNew;
        }
        #region 数据转换方法
        /// <summary>
        /// 传对应的sql语句进行查询数据
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataTable GetValuesTable(string sql)
        {

            OracleParameter[] param3 = new OracleParameter[] { };
            DataTable DtNew = OrcleHelper.ExecToSqlGetTable(sql.ToString(), param3, OrcleHelper.JhecisCon);
            if (DtNew != null && DtNew.Rows.Count > 0)
            {
                return DtNew;
            }
            return null;
        }
        public string ConvertTime(string time)
        {
            try
            {
                DateTime t = Convert.ToDateTime(time);
                string res = t.ToString("yyyyMMddHHmmss");
                return res;
            }
            catch (Exception)
            {
                return DateTime.Now.ToString("yyyyMMddHHmmss");
            }

        }
        private string NullDateTime = "00000000000000";
        public string ConvertTimeNoSend(string time)
        {
            try
            {
                DateTime t = Convert.ToDateTime(time);
                string res = t.ToString("yyyyMMddHHmm");
                return res;
            }
            catch (Exception)
            {
                return DateTime.Now.ToString("yyyyMMddHHmm");
            }
        }
        #endregion

        public int GetAgeByBirthdate(DateTime birthdate)
        {
            DateTime now = DateTime.Now;
            int age = now.Year - birthdate.Year;
            if (now.Month < birthdate.Month || (now.Month == birthdate.Month && now.Day < birthdate.Day))
            {
                age--;
            }
            return age < 0 ? 0 : age;
        }
        /// <summary>
        /// 通过pvid获取患者的多份病历
        /// </summary>
        /// <param name="pvid"></param>
        /// <returns></returns>
        public List<JZ_BL_Model> GetBLModelByPvid(string pvid)
        {
            List<JZ_BL_Model> Pat_BL_List = new List<JZ_BL_Model>();

            #region 诊断处理
            string diasql = "select DIAGNOSECODE,DIAGNOSENAME from pat_diagnose t  where t.deleteflag = 0 and pvid='" + pvid + "' ";
            DataTable DT_dia = GetValuesTable(diasql);
            string DiaXML = "";
            string DiagnoseName = "";
            string DiagnoseCode = "";
            if (DT_dia != null && DT_dia.Rows.Count > 0)
            {
                DiagnoseName = DT_dia.Rows[0]["DIAGNOSENAME"].ToString();
                DiagnoseCode = DT_dia.Rows[0]["DIAGNOSECODE"].ToString();
                for (int j = 0; j < DT_dia.Rows.Count; j++)
                {
                    string dianame = DT_dia.Rows[j]["DIAGNOSENAME"].ToString();
                    string diacode = DT_dia.Rows[j]["DIAGNOSECODE"].ToString();
                    DiaXML += "<component>";
                    DiaXML += "<observation classCode=\"OBS\" moodCode=\"EVN\">";
                    DiaXML += "<code code=\"" + diacode + "\" displayName=\"" + "" + "\" codeSystem=\"2.16.156.10011.2.2.1\" codeSystemName=\"卫生信息数据元目录\"/>";
                    DiaXML += "<value xsi:type=\"CD\" code=\"" + diacode + "\" displayName=\"" + dianame + "\" codeSystem=\"2.16.156.10011.2.3.3.11\" codeSystemName=\"ICD - 10\"/>";
                    DiaXML += "</component>";
                }
            }
            #endregion

            #region 查病历信息
            string sql_JBXX = @"SELECT
tp.patientname,
tp.INDENTITYNO,
case when tp.sex='男' then '男性' when tp.sex='女' then '女性' else '未知的性别' end sex,
case when tp.sex='男' then '1' when tp.sex='女' then '2' else '0' end SEXCODE,
tp.age,
tp.birthdate,
to_char(tp.birthdate,'yyyymmdd') BIRTHDATESTR,
ph.patientid,
ph.visitid ,
pi.DEPTCODE,
pi.DEPTNAME,
pi.operatorname,
to_char(pi.indepttime,'yyyymmddHHmmss') indepttime,
jf.file_unique_id,
jf.SHCZZT_FLAG,
jf.SIGN_USER_ID,
jf.SIGN_USER_NAME,
jf.MR_CLASS,
to_char(jf.create_date_time,'yyyymmddHHmmss') createtime,
to_char(jf.create_date_time,'yyyymmdd') createdate,
BLOB_TO_VARCHAR3(
(SELECT dg.DG_PLAIN_CONTENT_BLOB FROM JHMR_FILE_CONTENT_DG dg
WHERE dg.DG_CODE = 'S.04.006' and dg.file_unique_id = jf.file_unique_id)
) as GUOMINSHI,
BLOB_TO_VARCHAR3(
 (SELECT dg.DG_PLAIN_CONTENT_BLOB  FROM JHMR_FILE_CONTENT_DG dg
 WHERE dg.DG_CODE = 'S.01' and dg.file_unique_id =jf.file_unique_id)
 ) as ZHUSHU, 
BLOB_TO_VARCHAR3(
(SELECT dg.DG_PLAIN_CONTENT_BLOB FROM JHMR_FILE_CONTENT_DG dg
WHERE dg.DG_CODE = 'S.03' and dg.file_unique_id =jf.file_unique_id)
) as XIANBINGSHI, 
BLOB_TO_VARCHAR3(
(SELECT dg.DG_PLAIN_CONTENT_BLOB FROM JHMR_FILE_CONTENT_DG dg
WHERE dg.DG_CODE = 'S.04' and dg.file_unique_id =jf.file_unique_id)
) as JIWANGSHI,
BLOB_TO_VARCHAR3(
(SELECT dg.DG_PLAIN_CONTENT_BLOB FROM JHMR_FILE_CONTENT_DG dg
WHERE dg.DG_CODE = 'S.20' and dg.file_unique_id = jf.file_unique_id)
) as TIJIAN,
BLOB_TO_VARCHAR3(
(SELECT dg.DG_PLAIN_CONTENT_BLOB FROM JHMR_FILE_CONTENT_DG dg
WHERE dg.DG_CODE = 'S.05' and dg.file_unique_id = jf.file_unique_id)
) as FUZHUJIANCHA
from jhmr_file_index jf 
left join TRIAGE_PATIENTVISIT tp on jf.patient_id=tp.pvid
left join pat_hisvisitrecord ph on tp.pvid=ph.pvid
left join pat_patientinhouse pi on jf.patient_id=pi.pvid
where jf.delete_flag=0 and jf.mr_class in ('EMR16.00.02.00','EMR16.00.02.13')
and  jf.file_flag not in('T','0')
and jf.patient_id= '" + pvid + "' ";
            //
            DataTable hs = GetValuesTable(sql_JBXX);
            #endregion



            #region 病历信息赋值
            if (hs != null && hs.Rows.Count > 0)
            {
                for (int i = 0; i < hs.Rows.Count; i++)
                {
                    JZ_BL_Model VM_BL = new JZ_BL_Model();
                    DataRow r = hs.Rows[i];
                    VM_BL.PATIENTNAME = r["PATIENTNAME"].ToString();
                    VM_BL.PATIENTID = r["PATIENTID"].ToString();
                    VM_BL.VISITID = r["VISITID"].ToString();
                    VM_BL.AGE = "0";
                    try
                    {
                        DateTime BIRTHDATE = Convert.ToDateTime(r["BIRTHDATE"].ToString());
                        VM_BL.AGE = GetAgeByBirthdate(BIRTHDATE).ToString();
                    }
                    catch (Exception es)
                    {
                    }
                    VM_BL.INDENTITYNO = r["INDENTITYNO"].ToString();
                    if (string.IsNullOrEmpty(VM_BL.INDENTITYNO))
                    {
                        VM_BL.INDENTITYNO = "000000000000000000";
                    }
                    VM_BL.SEX = r["SEX"].ToString();
                    VM_BL.SEXCODE = r["SEXCODE"].ToString();
                    VM_BL.BIRTHDATESTR = r["BIRTHDATESTR"].ToString();
                    VM_BL.DEPTCODE = r["DEPTCODE"].ToString();
                    VM_BL.DEPTNAME = r["DEPTNAME"].ToString();
                    VM_BL.INDEPTTIME = r["INDEPTTIME"].ToString();
                    VM_BL.OPERATORNAME = r["OPERATORNAME"].ToString();
                    VM_BL.MR_CLASS = r["MR_CLASS"].ToString();
                    VM_BL.FILE_UNIQUE_ID = r["FILE_UNIQUE_ID"].ToString();
                    VM_BL.SHCZZT_FLAG = r["SHCZZT_FLAG"].ToString();
                    VM_BL.SIGN_USER_ID = r["SIGN_USER_ID"].ToString();
                    VM_BL.SIGN_USER_NAME = r["SIGN_USER_NAME"].ToString();
                    #region 病历内容
                    VM_BL.GUOMINSHI = r["GUOMINSHI"].ToString();
                    if (VM_BL.GUOMINSHI.Contains("无"))
                    {
                        VM_BL.GUOMINSHIFLAG = "false";
                    }
                    else 
                    {
                        VM_BL.GUOMINSHIFLAG = "true";
                    }
                    VM_BL.ZHUSHU = r["ZHUSHU"].ToString();
                    if (VM_BL.ZHUSHU.Contains("复诊"))
                    {
                        VM_BL.CHUZHENCODE = "2";
                        VM_BL.CHUZHENNAME = "复诊";
                    }
                    else
                    {
                        VM_BL.CHUZHENCODE = "1";
                        VM_BL.CHUZHENNAME = "初诊";
                    }
                    
                    VM_BL.XIANBINGSHI = r["XIANBINGSHI"].ToString();
                    VM_BL.JIWANGSHI = r["JIWANGSHI"].ToString();
                    VM_BL.TIJIAN = r["TIJIAN"].ToString();
                    VM_BL.FUZHUJIANCHA = r["FUZHUJIANCHA"].ToString();
                    if (string.IsNullOrEmpty(VM_BL.GUOMINSHI))
                    {
                        VM_BL.GUOMINSHI = "无。";
                    }
                    if (string.IsNullOrEmpty(VM_BL.ZHUSHU))
                    {
                        VM_BL.ZHUSHU = "无。";
                    }
                    if (string.IsNullOrEmpty(VM_BL.XIANBINGSHI))
                    {
                        VM_BL.XIANBINGSHI = "无。";
                    }
                    if (string.IsNullOrEmpty(VM_BL.JIWANGSHI))
                    {
                        VM_BL.JIWANGSHI = "无。";
                    }
                    if (string.IsNullOrEmpty(VM_BL.TIJIAN))
                    {
                        VM_BL.TIJIAN = "无。";
                    }
                    if (string.IsNullOrEmpty(VM_BL.FUZHUJIANCHA))
                    {
                        VM_BL.FUZHUJIANCHA = "无。";
                    }
                    #endregion
                    VM_BL.DiagnoseXML = DiaXML;
                    CDADiagnose CdaDia= ALLCDADia.Find(c => c.MATCH_CODE.Trim() == DiagnoseCode.Trim());
                    if (CdaDia != null)
                    {
                        VM_BL.DIAGNOSECODE = CdaDia.ITEM_CODE;
                        VM_BL.DIAGNOSENAME = CdaDia.ITEM_VALUE;
                    }
                    else 
                    {
                        VM_BL.DIAGNOSECODE = "R52.900";
                        VM_BL.DIAGNOSENAME = "疼痛";
                    }
                   
                    #region 查医嘱
                    if (!string.IsNullOrEmpty(VM_BL.VISITID))
                    {
                        DataTable DtOrder= GetPatientOrderInfo(VM_BL.PATIENTID, VM_BL.VISITID);
                        if (DtOrder != null && DtOrder.Rows.Count > 0)
                        {
                            string ordertimestr = DtOrder.Rows[0]["ORDER_TIME"].ToString();
                            string orderClass = DtOrder.Rows[0]["ORDER_CLASS_CODE"].ToString();
                            switch (orderClass)
                            {
                                case "01":
                                    VM_BL.ORDER_CLASS_CODE = "01";
                                    VM_BL.ORDER_CLASS_NAME = "药品类医嘱";
                                    break;
                                case "03":
                                    VM_BL.ORDER_CLASS_CODE = "03";
                                    VM_BL.ORDER_CLASS_NAME = "检验类医嘱";
                                    break;
                                case "04":
                                    VM_BL.ORDER_CLASS_CODE = "02";
                                    VM_BL.ORDER_CLASS_NAME = "检查类医嘱";
                                    break;
                                default:
                                    VM_BL.ORDER_CLASS_CODE = "99";//05处置类医嘱
                                    VM_BL.ORDER_CLASS_NAME = "其他医嘱";
                                    break;
                            }

                            VM_BL.ORDER_TIME = ConvertTime(ordertimestr);
                            if (string.IsNullOrEmpty(VM_BL.ORDER_TIME))
                            {
                                VM_BL.ORDER_TIME = NullDateTime;
                            }
                            VM_BL.ORDER_ITEM_NAME = DtOrder.Rows[0]["ORDER_ITEM_NAME"].ToString();
                            if (string.IsNullOrEmpty( VM_BL.ORDER_ITEM_NAME))
                            {
                                VM_BL.ORDER_ITEM_NAME = "无";
                            }
                            VM_BL.PRESC_OPERA = DtOrder.Rows[0]["PRESC_OPERA"].ToString();
                            VM_BL.PRESC_NAME = DtOrder.Rows[0]["PRESC_NAME"].ToString();
                            VM_BL.PRESC_DEPT_CODE = DtOrder.Rows[0]["PRESC_DEPT_CODE"].ToString();
                            VM_BL.PRESC_DEPT_NAME = DtOrder.Rows[0]["PRESC_DEPT_NAME"].ToString();
                            VM_BL.PRESC_TIME = ConvertTime(DtOrder.Rows[0]["PRESC_TIME"].ToString());
                            VM_BL.SH_TIME = ConvertTime(DtOrder.Rows[0]["SH_TIME"].ToString());
                            VM_BL.ORDER_NOTE = DtOrder.Rows[0]["ORDER_NOTE"].ToString();
                            VM_BL.PRES_STATUS_CODE = DtOrder.Rows[0]["PRES_STATUS_CODE"].ToString();

                            VM_BL.ORDER_DOCTOR_NAME = DtOrder.Rows[0]["ORDER_DOCTOR_NAME"].ToString();
                            VM_BL.ORDER_DEPT_NAME = DtOrder.Rows[0]["ORDER_DEPT_NAME"].ToString();
                            VM_BL.SH_DOCTOR_NAME = DtOrder.Rows[0]["SH_DOCTOR_NAME"].ToString();
                            //VM_BL.ORDER_NOTE = DtOrder.Rows[0]["ORDER_NOTE"].ToString();
                        }
                        else
                        {
                            //没有医嘱
                            VM_BL.ORDER_CLASS_CODE = "99";//05处置类医嘱
                            VM_BL.ORDER_CLASS_NAME = "其他医嘱";
                            VM_BL.ORDER_TIME = NullDateTime;
                            VM_BL.ORDER_ITEM_NAME = "";
                            VM_BL.PRESC_OPERA = "";
                            VM_BL.PRESC_NAME = "";
                            VM_BL.PRESC_DEPT_CODE = "";
                            VM_BL.PRESC_DEPT_NAME = "";
                            VM_BL.PRESC_TIME = NullDateTime;
                            VM_BL.SH_TIME = NullDateTime;
                            VM_BL.ORDER_NOTE = "";
                            VM_BL.PRES_STATUS_CODE = "";

                            VM_BL.ORDER_DOCTOR_NAME = "";
                            VM_BL.ORDER_DEPT_NAME = "";
                            VM_BL.SH_DOCTOR_NAME = "";
                        }
                    }

                    #endregion
                    #region 文档信息
                    VM_BL.P_GUID = VM_BL.FILE_UNIQUE_ID;
                    VM_BL.P_CREATETIME = r["CREATETIME"].ToString();
                    VM_BL.P_CREATEDATE = r["CREATEDATE"].ToString();
                    VM_BL.P_VISITID = r["VISITID"].ToString();
                    VM_BL.P_PATIENTID = r["PATIENTID"].ToString();
                    VM_BL.P_HOSNO = "";
                    VM_BL.P_INDENTITYNO = VM_BL.INDENTITYNO;
                    VM_BL.P_PATIENTNAME = VM_BL.PATIENTNAME;
                    VM_BL.P_DOCTORID = VM_BL.SIGN_USER_ID;
                    if (string.IsNullOrEmpty(VM_BL.P_DOCTORID))
                    {
                        VM_BL.P_DOCTORID = "000";
                    }
                    VM_BL.P_DOCTORNAME = VM_BL.SIGN_USER_NAME;
                    if (string.IsNullOrEmpty(VM_BL.P_DOCTORNAME))
                    {
                        VM_BL.P_DOCTORNAME = "无";
                    }
                    VM_BL.P_DEPTCODE = VM_BL.DEPTCODE;
                    VM_BL.P_DEPTNAME = VM_BL.DEPTNAME;
                    #endregion
                    Pat_BL_List.Add(VM_BL);
                }
            }
            #endregion
            return Pat_BL_List;
        }

        public DataTable GetPatientOrderInfo(string patientid, string visitid)
        {
            StringBuilder str = new StringBuilder();//JH_MZ_ORDER
            str.Append("select * from chisdb_dev.JH_MZ_ORDER jh where  jh.OUT_PATIENT_ID='" + patientid + "' and VISIT_ID='" + visitid + "'  order by jh.ORDER_CLASS_code");
            OracleParameter[] param3 = new OracleParameter[] { };
            DataTable DtOrder = OrcleHelper.ExecToSqlGetTable(str.ToString(), param3, OrcleHelper.JhecisCon);
            return DtOrder;
        }
    }
}
